﻿package  {
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Loader;
	import flash.display.MovieClip;
	import flash.display.Sprite;
	
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.MouseEvent;
	import flash.events.TimerEvent;
	
	import flash.net.URLLoader;
    import flash.net.URLRequest;
    import flash.net.URLRequestMethod;
	import flash.net.URLVariables;
	
	import flash.utils.Timer;
	
	// 对JSON的支持
    import json.JSON;
    import flash.geom.Rectangle;
    import flash.geom.Point;

	public class MainPanel extends MovieClip {
		private var round:uint;
		private var imgRound:uint;
		private var cellWidth:uint;
		private var maxNum:uint;
		
		private const stageTop = 93;
		private const stageLeft = 59;
		private const stageConstWidth = 420;
		
		private const viewTop = 334;
		private const viewLeft = 544;
		
		private var loadFlag:Boolean = false;
		private var loader:Loader;
		
		private var rdmArr:Array;
		
		private var backImgView:Sprite;
		
		private var refreshCount:uint;
		private var timer:Timer;
		private var timeCount:uint;
		private var timePlus:uint;
		private var timeArr:Array = [200, 250, 300];
		private var score:int;
		
		private var exchangeMode:Boolean = false;
		private var exchangeCount:uint;
		private var exchangeCell:Cell;
		
		private const panelLeft = 200;
		private const panelTop = 150;
		private var showReadyFlag:Boolean = true;
		private var readyPanel:ReadyPanel;
		private var successPanel:SuccessPanel;
		private var endPanel:EndPanel;
		
		//json交互必须参数
		private var appKey:String;
		private var user_id:int;
		
		public function MainPanel() {
			//showJSON();
			
			this.refreshBtn.addEventListener(MouseEvent.CLICK, refreshBtnHandler);
			this.exchangeBtn.addEventListener(MouseEvent.CLICK, exchangeBtnHandler);
			
			readyPanel = new ReadyPanel();
			readyPanel.goBtn.addEventListener(MouseEvent.CLICK, goBtnHandler);
			
			successPanel = new SuccessPanel();
			successPanel.refreshBtn.addEventListener(MouseEvent.CLICK, refreshGiftHandler);
			successPanel.exchangeBtn.addEventListener(MouseEvent.CLICK, exchangeGiftHandler);
			successPanel.timeBtn.addEventListener(MouseEvent.CLICK, timeGiftHandler);
			
			endPanel = new EndPanel();
			endPanel.againBtn.addEventListener(MouseEvent.CLICK, againBtnHandler);
			endPanel.uploadBtn.addEventListener(MouseEvent.CLICK, uploadBtnHandler);
			
			timePlus = 0;
			
			round = 4;
			imgRound = 1;
			
			refreshCount = 10;
			this.refreshBtn.refreshTimes.text = refreshCount;
			
			exchangeCount = 10;
			this.exchangeBtn.exchangeTimes.text = exchangeCount;
			
			score = 100;
			this.scoreTxt.text = String(score);
			
			//底图准备
			loadbackImg();
						
			init();
		}
		
		//初始化
		private function init(){
			maxNum = round * round;
			cellWidth = uint(stageConstWidth / round);
			
			timeCount = timeArr[round - 4] + timePlus;
			this.timeCountTxt.text = String(timeCount);
			timer = new Timer(1000, timeArr[round - 4] + timePlus);
			timer.addEventListener(TimerEvent.TIMER, timerCountHandler);
			timer.addEventListener(TimerEvent.TIMER_COMPLETE, gameOverHandler);
			timePlus = 0;
			
			getInitArr();
		}
		
		//计算初始矩阵
		private function getInitArr(){
			rdmArr = new Array(maxNum);
			
			var tmpArr:Array = new Array(maxNum - 1);
			for(var rdmI:uint = 0; rdmI < maxNum - 1; rdmI ++){
				tmpArr[rdmI] = rdmI + 1;
			}
			
			for(var rdmJ:uint = 0; rdmJ < maxNum - 1; rdmJ ++){
				var tmpIndex:uint = uint(Math.random() * tmpArr.length);
				rdmArr[rdmJ] = tmpArr[tmpIndex];
				tmpArr.splice(tmpIndex, 1);
			}
			
			rdmArr[maxNum - 1] = 0;
		}
		
		//单元格就位
		private function cellReady(){
			var bt:BitmapData = Bitmap(loader.content).bitmapData;
			var pt:Point = new Point(0, 0);
			
			backImgView = new Sprite();
			var backImgBtmp:Bitmap = new Bitmap(new BitmapData(stageConstWidth, stageConstWidth));
			var rectback:Rectangle = new Rectangle(0, 0, stageConstWidth, stageConstWidth);
			backImgBtmp.bitmapData.copyPixels(bt, rectback, pt);
			backImgView.addChild(backImgBtmp);
			this.addChild(backImgView);
			backImgView.scaleX = 0.4;
			backImgView.scaleY = 0.4;
			backImgView.x = viewLeft;
			backImgView.y = viewTop;
			
			for(var cellI:uint = 0; cellI < maxNum - 1; cellI ++){ 
				var tmpRdm:uint = rdmArr[cellI] as uint;
				var tmpLeft:uint = (tmpRdm - 1) % round;
				var tmpTop:uint = uint((tmpRdm - 1) / round);
				
				var cellBtmp:Bitmap = new Bitmap(new BitmapData(cellWidth, cellWidth));
				var rect:Rectangle = new Rectangle(tmpLeft * cellWidth, tmpTop * cellWidth, cellWidth, cellWidth);
				cellBtmp.bitmapData.copyPixels(bt, rect, pt);
				
				var cellSp:Cell = new Cell(cellI + 1, tmpRdm);
				cellSp.addChild(cellBtmp);
				cellSp.scaleX = 0.9;
				cellSp.scaleY = 0.9;
				
				this.addChild(cellSp);
				cellSp.addEventListener(MouseEvent.CLICK, cellClickHandler);
				
				tmpLeft = cellI % round;
				tmpTop = uint(cellI / round);
				cellSp.x = tmpLeft * cellWidth + stageLeft;
				cellSp.y = tmpTop * cellWidth + stageTop;
			}
			
			if(showReadyFlag){
				this.addChild(readyPanel);
				readyPanel.x = panelLeft;
				readyPanel.y = panelTop;
			}
		}
		
		//加载拼图图片
		private function loadbackImg(){
			var urlRequest:URLRequest = new URLRequest("backimg" + imgRound + ".jpg");
			loader = new Loader();
			loader.load(urlRequest);
			loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
            loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loaderCompleteHandler);
		}
		
		private function errorHandler(e:IOErrorEvent){
			loader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, errorHandler);
            loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, loaderCompleteHandler);
			cellReady();
		}
		
		private function loaderCompleteHandler(e:Event){
			loader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, errorHandler);
            loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, loaderCompleteHandler);
			loadFlag = true;
			cellReady();
		}
		
		//单元格点击事件
		private function cellClickHandler(e:MouseEvent){
			var cell:Cell = e.target as Cell;
			var cpid:uint = cell.currentPosId - 1;
			
			if(exchangeMode){//交换
				if(exchangeCell == null)
					exchangeCell = cell;
				else{
					var tmpPosId = exchangeCell.currentPosId - 1;
					cell.currentPosId = tmpPosId + 1;
					var tmpX = tmpPosId % round;
					cell.x = tmpX * cellWidth + stageLeft;
					var tmpY = uint(tmpPosId / round);
					cell.y = tmpY * cellWidth + stageTop;
					
					exchangeCell.currentPosId = cpid + 1;
					tmpX = cpid % round;
					exchangeCell.x = tmpX * cellWidth + stageLeft;
					tmpY = uint(cpid / round);
					exchangeCell.y = tmpY * cellWidth + stageTop;
					
					rdmArr[cpid] = exchangeCell.realPosId;
					rdmArr[tmpPosId] = cell.realPosId;
					
					exchangeCell = null;
					
					exchangeCount --;
					this.exchangeBtn.exchangeTimes.text = exchangeCount;
					exchangeMode = false;
					
					isFinish();
				}
			}
			else{//移动
				var tmpUint:uint = rdmArr[cpid];
				if((cpid + 1) % round != 0){
					//右
					if(rdmArr[cpid + 1] == 0){
						moveCell(cell, cpid, tmpUint, cellWidth, 0, 1);
						return;
					}
				}
				if(cpid < maxNum - round){
					//下
					if(rdmArr[cpid + round] == 0){
						moveCell(cell, cpid, tmpUint, 0, + cellWidth, round);
						return;
					}
				}
				if((cpid + 1) % round != 1){
					//左
					if(rdmArr[cpid - 1] == 0){
						moveCell(cell, cpid, tmpUint, - cellWidth, 0, - 1);
						return;
					}
				}
				if(cpid + 1 > round){
					//上
					if(rdmArr[cpid - round] == 0){
						moveCell(cell, cpid, tmpUint, 0, - cellWidth, - round);
					}
				}
			}
		}
		
		private function moveCell(cell:Cell, crntId:uint, realId:uint, xMove:int, yMove:int, currentPosPlug:int){
			cell.x += xMove;
			cell.y += yMove;
			cell.currentPosId += currentPosPlug;
			rdmArr[crntId + currentPosPlug] = realId;
			rdmArr[crntId] = 0;
			isFinish();
		}
		
		//判断是否完成
		private function isFinish(){
			score --;
			this.scoreTxt.text = String(score);
			
			var tmpFlag:Boolean = true;
			for(var i:uint = 0; i < maxNum - 1; i ++){
				if(rdmArr[i] != i + 1){
					tmpFlag = false;
					break;
				}
			}
			
			if(tmpFlag){
				for(var j:uint = 0; j < maxNum - 1; j ++){
					this.removeChildAt(this.numChildren - 1);
				}
				
				timer.stop();
				timer.removeEventListener(TimerEvent.TIMER, timerCountHandler);
				timer.removeEventListener(TimerEvent.TIMER_COMPLETE, gameOverHandler);
				
				backImgView.scaleX = 0.98;
				backImgView.scaleY = 0.98;
				backImgView.x = stageLeft;
				backImgView.y = stageTop;
				
				this.addChild(successPanel);
				successPanel.x = panelLeft;
				successPanel.y = panelTop;
				
				successPanel.oldScore.text = String(score);
				successPanel.timeLeft.text = String(timeCount);
				successPanel.newScore.text = String(score + timeCount * 10);
			}
		}
		
		//过关操作
		private function nextRoundHandler(){
			this.removeChild(successPanel);
			this.removeChild(backImgView);
			
			round ++;
			
			score += timeCount * 10;
			this.scoreTxt.text = String(score);
			
			if(round == 7){
				round = 4;
				init();
				
				if(imgRound == 3){
					this.addChild(endPanel);
					endPanel.x = panelLeft;
					endPanel.y = panelTop;
					endPanel.newScore.text = String(score);
					
					return;
				}
				
				imgRound ++;
				
				loader.unload();
				loadbackImg();
			}
			else{
				showReadyFlag = true;
				init();
				cellReady();
			}
		}
		
		//刷新功能
		private function refreshBtnHandler(e:MouseEvent){
			if(refreshCount > 0){
				refreshCount --;
				this.refreshBtn.refreshTimes.text = refreshCount;
				
				for(var j:uint = 0; j < maxNum; j ++){
					this.removeChildAt(this.numChildren - 1);
				}
				
				showReadyFlag = false;
				
				getInitArr();
				cellReady();
			}
		}
		
		//时间读秒
		private function timerCountHandler(e:TimerEvent){
			timeCount --;
			this.timeCountTxt.text = String(timeCount);
		}
		
		//时间结束
		private function gameOverHandler(e:TimerEvent){
			timer.removeEventListener(TimerEvent.TIMER, timerCountHandler);
			timer.removeEventListener(TimerEvent.TIMER_COMPLETE, gameOverHandler);
			
			this.addChild(endPanel);
			endPanel.x = panelLeft;
			endPanel.y = panelTop;
			endPanel.newScore.text = String(score);
		}
		
		//启动秘密武器
		private function exchangeBtnHandler(e:MouseEvent){
			if(exchangeCount > 0)
				exchangeMode = true;
		}
		
		//过关奖励
		private function refreshGiftHandler(e:MouseEvent){
			refreshCount += 2;
			this.refreshBtn.refreshTimes.text = refreshCount;
			
			nextRoundHandler();
		}
		
		private function exchangeGiftHandler(e:MouseEvent){
			exchangeCount ++;
			this.exchangeBtn.exchangeTimes.text = exchangeCount;
			
			nextRoundHandler();
		}
		
		private function timeGiftHandler(e:MouseEvent){
			timePlus = 50;
			
			nextRoundHandler();
		}
		
		//再玩一次
		private function againBtnHandler(e:MouseEvent){
			this.removeChild(endPanel);
			
			for(var j:uint = 0; j < maxNum; j ++){
				this.removeChildAt(this.numChildren - 1);
			}
			
			init();
		}		
		
		//与微博交互，提交成绩
		private function uploadBtnHandler(e:MouseEvent){
			this.removeChild(endPanel);
			
			/*for(var j:uint = 0; j < maxNum; j ++){
				this.removeChildAt(this.numChildren - 1);
			}*/
			
			var v:URLVariables = new URLVariables();
			v.source = appKey;
			v.timestamp = flash.utils.getTimer();
			v.rank_id = 0;
			v.value = score;
            var r:URLRequest = new URLRequest();
            r.url = "http://api.weibo.com/game/1/leaderboards/set.json";
            r.method = URLRequestMethod.POST;
            r.data = v;
            
            var l:URLLoader = new URLLoader();
            l.load(r);
            l.addEventListener(Event.COMPLETE, jsonCompleteHandler);
		}
		
		private function goBtnHandler(e:MouseEvent){
			this.removeChild(readyPanel);
			
			timer.start();
		}
		
		// 以JSON形式通信
        function showJSON():void
        {
            var v:URLVariables = new URLVariables();
			v.source = appKey;
			v.timestamp = flash.utils.getTimer();
            var r:URLRequest = new URLRequest();
            r.url = "http://api.weibo.com/game/1/application/is_user.json";
            r.method = URLRequestMethod.GET;
            r.data = v;
            
            var l:URLLoader = new URLLoader();
            l.load(r);
            l.addEventListener(Event.COMPLETE, jsonCompleteHandler);
        }
        
        function jsonCompleteHandler(event:Event):void
        {
            var l:URLLoader = event.target as URLLoader;
            
            var v:* = JSON.decode(l.data);
            
            trace("姓名：" + v.uid + "；年龄：" + v.flag, v.msg);
			trace("姓名：" + v.request + "；年龄：" + v.error_code, v.error);
            
        }
	}
}
